package com.security.demo.controller;

import com.security.demo.utils.CodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
@RequestMapping("/public")
@CrossOrigin
@Slf4j
public class PublicController {

    /**
     * 生成验证码图片
     */
    @GetMapping("/code")
    public void code(HttpServletRequest request, HttpServletResponse response) throws IOException {
        CodeUtil code = new CodeUtil();
        // 生成验证码图片
        BufferedImage image = code.getImage();
        String text = code.getText();
        log.info("验证码是： {}", text);
        // 将验证码储存在session中
        request.getSession().setAttribute("code", text);
        // 响应验证码图片
        CodeUtil.output(image, response.getOutputStream());
    }

}
